package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;

import com.itheima.utils.MD5Utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 会员管理
 */
@RestController
@RequestMapping("/member")
public class MemberController {

    @Autowired
    private JedisPool jedisPool;
    @Reference
    private MemberService memberService;

    //手机验证码登录
    @RequestMapping("/login")
    public Result login(HttpServletResponse response,@RequestBody Map map){
        String telephone = (String) map.get("telephone");
        String validateCode = (String) map.get("validateCode");
        //从redis中获取提前保存的验证码
        String codeInRedis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);
        //1、校验用户输入的短信验证码是否正确，如果验证码错误则登录失败
        if(codeInRedis == null || !codeInRedis.equals(validateCode)){
            //验证码错误
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }

        //2、如果验证码正确，则判断当前用户是否为会员，如果不是会员则自动完成会员注册
        Member member = memberService.findByTelephone(telephone);
        if(member == null){
            //不是会员，需要自动注册
            member = new Member();
            member.setPhoneNumber(telephone);
            member.setRegTime(new Date());
            memberService.add(member);
        }

        //3、向客户端写入Cookie，内容为用户手机号
        String s = MD5Utils.md5(telephone);
        Cookie cookie = new Cookie("member_login_telephone",s);

        cookie.setPath("/");
        cookie.setMaxAge(60 * 60 * 24 * 30);
        //将Cookie写入到客户端浏览器
        response.addCookie(cookie);

        //4、将会员信息保存到Redis，使用手机号作为key，保存时长为30分钟
        jedisPool.getResource().setex(s,60 * 30, JSON.toJSON(member).toString());
        return new Result(true,MessageConstant.LOGIN_SUCCESS);
    }





    //获取登录用户的回显数据
    @RequestMapping("/getmember")
    public Result getmember(HttpServletRequest request){
        //设置手机号的接收变量
        String telephone=null;
        try {

            Cookie[] cookies = request.getCookies();
            if (cookies!=null){
                for (Cookie cookie : cookies) {
                    String name = cookie.getName();
                    if (name.equals("member_login_telephone")){
                        //遍历cookie数组拿到带有手机号码的cookie名字
                        //如果相同就把手机号赋值给变量，然后退出
                        telephone=cookie.getValue();
                        break;
                    }
                }
                //拿到手机号
                if (telephone!=null){
                    //获取回显数据
                    String idRedis = jedisPool.getResource().get(telephone);
                    //如果redis不为空，证明已经登录过了
                    if (idRedis!=null){
                        //查询数据库把数据回显给页面
                        Member member = JSON.parseObject(idRedis, Member.class);
                        return new Result(true,MessageConstant.GET_USER_SUCCESS,member);
                    }else {
                        //redis为空
                        return new Result(false,MessageConstant.GET_USER_FAIL);
                    }

                }else {
                    //手机号为空
                    return new Result(false,MessageConstant.GET_USER_FAIL);
                }

            }else {
                //cookie为空
                return new Result(false,MessageConstant.GET_USER_FAIL);
            }
        } catch (Exception e) {
            //程序访问报错
            e.printStackTrace();
            return  new Result(false,MessageConstant.GET_USER_FAIL);
        }

    }



    //获取修改用户的数据
    @RequestMapping("/updatemember")
    public Result updatemember(@RequestBody Member member,HttpServletRequest request){

        try {

                //拿到加密的cookie
                String s=null;
                Cookie[] cookies = request.getCookies();
                if (cookies!=null){
                    for (Cookie cookie : cookies) {
                        String name = cookie.getName();
                        if (name.equals("member_login_telephone")){
                            //遍历cookie数组拿到带有手机号码的cookie名字
                            //如果相同就把手机号赋值给变量，然后退出
                            s=cookie.getValue();
                            break;
                        }
                    }
                }else {
                    //cookie为空
                    return new Result(false,MessageConstant.GET_USER_FAIL);
                }

            memberService.updateId(member);
            jedisPool.getResource().setex(s,60 * 30, JSON.toJSON(member).toString());
            return new Result(true,MessageConstant.EDIT_USER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.EDIT_USER_FAIL);
        }
    }

    @RequestMapping("/getSetmeal")
    public Result updatemember(HttpServletRequest request) {
        String telephone=null;
        try {
            Cookie[] cookies = request.getCookies();
            if (cookies!=null){
                for (Cookie cookie : cookies) {
                    String name = cookie.getName();
                    if (name.equals("member_login_telephone")){
                        //遍历cookie数组拿到带有手机号码的cookie名字
                        //如果相同就把手机号赋值给变量，然后退出
                        telephone=cookie.getValue();
                        break;
                    }
                }
                //拿到手机号
                if (telephone!=null){
                    //获取回显数据
                    String idRedis = jedisPool.getResource().get(telephone);
                    //如果redis不为空，证明已经登录过了
                    if (idRedis!=null){
                        //查询数据库把数据回显给页面
                        Member member = JSON.parseObject(idRedis, Member.class);
                        Integer id = member.getId();
                        List<Map<String, Object>> map = memberService.findByIds(id);
                        return new Result(true,MessageConstant.GET_USERS_SUCCESS,map);
                    }
                }
            }
        } catch (Exception e) {
            //程序访问报错
            e.printStackTrace();
            return  new Result(false,MessageConstant.GET_USERS_FAIL);
        }
        return  new Result(false,"获取个人信息失败了");
    }



    @RequestMapping("/getByDate")
    public Result getByDate(String startTime,String endTime,HttpServletRequest request) {
        String telephone=null;
        try {
            Cookie[] cookies = request.getCookies();
            if (cookies!=null){
                for (Cookie cookie : cookies) {
                    String name = cookie.getName();
                    if (name.equals("member_login_telephone")){
                        //遍历cookie数组拿到带有手机号码的cookie名字
                        //如果相同就把手机号赋值给变量，然后退出
                        telephone=cookie.getValue();
                        break;
                    }
                }
                //拿到手机号
                if (telephone!=null){
                    //获取回显数据
                    String idRedis = jedisPool.getResource().get(telephone);
                    //如果redis不为空，证明已经登录过了
                    if (idRedis!=null){
                        //查询数据库把数据回显给页面
                        Member member = JSON.parseObject(idRedis, Member.class);
                        Integer id = member.getId();
                        List<Map<String, Object>> map = memberService.findByDate(id,startTime,endTime);
                        return new Result(true,MessageConstant.GET_USERS_SUCCESS,map);
                    }
                }
            }
        } catch (Exception e) {
            //程序访问报错
            e.printStackTrace();
            return  new Result(false,MessageConstant.GET_USERS_FAIL);
        }
        return  new Result(false,"获取个人信息失败了");
    }

    @RequestMapping("/getAll")
    public Result getAll(String id) {
        try {
            Map<String,Object> map=memberService.getAll(id);
            return new Result(true,MessageConstant.GET_USERSS_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_USERSS_FAIL);
        }
    }

}
